package cn.corgy.module.serialize.fst;

import cn.corgy.exception.SerializeException;
import cn.corgy.module.serialize.Serializer;
import org.nustaq.serialization.FSTConfiguration;
import org.nustaq.serialization.FSTObjectInput;
import org.nustaq.serialization.FSTObjectOutput;

/**
 * fst序列化
 */
public class FstSerializer implements Serializer {

    FSTConfiguration conf = FSTConfiguration.createAndroidDefaultConfiguration();

    @Override
    public byte[] serialize(Object obj) {
        try (FSTObjectOutput objectOutput = conf.getObjectOutput();) {
            objectOutput.writeObject(obj);

            return objectOutput.getCopyOfWrittenBuffer();
        } catch (Exception e) {
            throw new SerializeException("Serialization failed");
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {

        try (FSTObjectInput objectInput = conf.getObjectInput(bytes);) {
            Object obj = objectInput.readObject();

            return clazz.cast(obj);

        } catch (Exception e) {
            throw new SerializeException("Deserialization failed");
        }
    }
}
